#include "List.h"
#include<assert.h>
#include<stdlib.h>
struct ListNode* InitList()                                          
{
	ListNode* phead = (struct ListNode*)malloc(sizeof(ListNode));                                //直接在函数内部分配空间
	phead->next = phead;                                                                         //两个指针,一个指向前一个结点,一个指向后一个结点
	phead->prev = phead;
	return phead;
}

struct ListNode* BuyListNode(ListDateType x)                       //分配空间+赋值
	struct ListNode* newnode = (struct ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		return NULL;
	}
	newnode->val = x;
	newnode->next = NULL;                                    
	newnode->prev = NULL;
	return newnode;
}

void ListPushFront(ListNode* phead, ListDateType x)    //前插
{
	assert(phead);
	struct ListNode* newnode = BuyListNode(x);
	struct ListNode* next = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = next;
	next->prev = newnode;                                             

void ListPopFront(ListNode* phead)                      //前删              
	assert(phead->next != phead);
	struct ListNode* next = phead->next;
	struct ListNode* nnext = next->next;
	phead->next = nnext;
	nnext->prev = phead;
	free(next);
	next = NULL;
}

void ListPrint(ListNode* phead)                          //打印              
{
	ListNode* cur = phead -> next;
	while (cur != phead)
	{
		printf("%d->", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushBack(ListNode* phead, ListDateType x)       //后插
{
	assert(phead);
	ListNode* tail = phead->prev;

	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	assert(newnode);
	newnode->val = x;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListPopBack(ListNode* phead)                //后删                            
{
	assert(phead);
	assert(phead->next != phead);  
	ListNode* tail = phead->prev;
	ListNode* tprev = tail->prev;
	tprev->next = phead;
	phead->prev = tprev;
	free(tail);
	tail = NULL;
}

struct ListNode* ListFind(ListNode* phead, ListDateType x)           //查找值
{
	int i = 1;
	struct ListNode* cur = phead->next;
	while (cur->next != phead)
	{
		if (cur->val == x)
		{
			return cur;
			break;
		}
		i++;
		cur = cur->next;
	}
	return NULL;
}

void ListDestroy(struct ListNode* phead)                       //销毁
{
	assert(phead);
	struct ListNode* cur = phead->next;                      
	while (cur->next != phead)                             
	{                                                      
		struct LisstNode* next = cur->next;
		free(cur);
		cur = NULL;
		cur = next;
	}
	free(phead);                                          
	phead = NULL;                                        
}